//
//  UserAccount.swift
//  我的微博
//
//  Created by ZhangChao on 15/9/6.
//  Copyright © 2015年 ZhangChao. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {

//    "access_token" = "2.00wIAyMG8PB31B72d9ef191buppWZB";
//    "expires_in" = 157679999;
//    "remind_in" = 157679999;// 这个参数即将废弃,建议使用上面的那一个
//    uid = 5688413258;
    
    var access_token: String?
    // 这里要判断过期日期
    var expires_in: NSTimeInterval = 0{
        didSet{
            // 计算过期日期
            expriesDate = NSDate(timeIntervalSinceNow: expires_in)
            
        }
        
    }
    
    var uid: String?
    
    var expriesDate: NSDate?
    
    // 加载用户数据
    var name: String? //用户好友名称
    var avatar_large: String? // 大头像
    
    
    init(dict:[String : AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey: String){}
    
    override var description: String{
        
        let key = ["access_token","expires_in","expriesDate","uid", "name","avatar_large"];
        
        return dictionaryWithValuesForKeys(key).description
    }
    // 对象属性的保存路径
    static let accountPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString) .stringByAppendingPathComponent("userAccount.plist")
    // 将当前对象保存
    func saveUserAccount(){
        
        // 对象函数中调用静态属性需要加上类名
        printLog("保存路径" + UserAccount.accountPath)
        
        // 键值归档
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
        
    }
    // 加载用户账号 让这个函数在哪里都可以调用,所以写成类函数
    // 如果用户没有登录 就返回nil
    class func loadUserAccount() -> UserAccount? {
        
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        
        if let date = account?.expriesDate{
            
            // 判断token是否过期,和现在的系统时间进行比较,OrderedDescending降序排列
            if date.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                
                return account
            }
        }
        
        return account
    }
    
    
    
    // 归档和解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey:"access_token")
        aCoder.encodeObject(expriesDate, forKey:"expriesDate")
        aCoder.encodeObject(uid, forKey:"uid")
        aCoder.encodeObject(name, forKey:"name")
        aCoder.encodeObject(avatar_large, forKey:"avatar_large")
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expriesDate = aDecoder.decodeObjectForKey("expriesDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
        
    }
}
